<?php

namespace adminmatrix\server\command\make;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

abstract class Make extends Command
{
    protected  array $type = [
        'model' , 'controller' , 'lists' , 'logic' , 'validate'
    ];

//    abstract protected function getStub();

    protected function configure()
    {
        $this->addArgument('name', Argument::REQUIRED, "The name of the class");
    }

    protected function execute(Input $input, Output $output)
    {
        $name = trim($input->getArgument('name'));
        $classname = $this->getClassName($name);
        # 处理控制器层


        foreach ($classname as $key => $value)
        {
            $pathName = $this->getPathName($value);
            if (is_file($pathName))
            {
                $output->writeln('<error>' . $key . ':' . $value . ' already exists!</error>');
                continue;
            }
            if (!is_dir(dirname($pathName)))
            {
                mkdir(dirname($pathName), 0755, true);
            }
//            dump($this->buildClass($value , $key));
            file_put_contents($pathName , $this->buildClass($value , $key));
            $output->writeln('<info>' . $key . ':' . $value . ' created successfully.</info>');

        }


    }

    protected function buildClass(string $name , $key)
    {
        $stubPath = __DIR__ . DIRECTORY_SEPARATOR . 'create'  . DIRECTORY_SEPARATOR. $key . '.stub';
        if (file_exists($stubPath))
        {
            $stub = file_get_contents($stubPath);
            $namespace = trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');
            $class = str_replace($namespace . '\\', '', $name);

            switch ($key){
                case 'controller':
                    $model = str_replace(["controller","Controller"],["logic","Logic"],$name);
                    return str_replace(['{%namespace%}' , '{%className%}' , '{%actionSuffix%}' , '{%USE%}' , '{%LOGIC%}'] ,[
                        $namespace,
                        $class,
                        $this->app->config->get('route.action_suffix'),
                        "use $model",
                        str_replace("Controller" , "Logic" , $class),
                    ],$stub);
                case 'model':
                    return str_replace(['{%namespace%}' , '{%className%}' , '{%actionSuffix%}'] ,[
                        $namespace,
                        $class,
                        $this->app->config->get('route.action_suffix'),
                    ],$stub);

                case 'validate':

                    return str_replace(['{%namespace%}' , '{%className%}' , '{%actionSuffix%}'] ,[
                        $namespace,
                        $class . "Validate",
                        $this->app->config->get('route.action_suffix'),
                    ],$stub);
                case 'logic':
                    $model = str_replace(["logic","Logic"],["model",""],$name);
                    $validate = str_replace(["logic","Logic"],["validate","Validate"],$name);
                    $name =  str_replace("Logic", "" , $class);

                    return str_replace(['{%namespace%}' , '{%className%}' , '{%actionSuffix%}' , '{%USE%}','{%name%}' ,"{%USEVALIDATE%}"] ,[
                        $namespace,
                        $class,
                        $this->app->config->get('route.action_suffix'),
                        $model . " as {$name}Model",
                        "{$name}Model",
                        "{$validate}"
                    ],$stub);
                case 'lists':
                    $model = str_replace(["logic","Logic"],["model",""],$name);
                    $name =  str_replace("Logic", "" , $class);
                    return str_replace(['{%namespace%}' , '{%className%}' , '{%actionSuffix%}' , '{%USE%}','{%name%}'] ,[
                        $namespace,
                        $class,
                        $this->app->config->get('route.action_suffix'),
                        $model . " as {$name}Model",
                        "{$name}Model",
                    ],$stub);

            }
        }

//        $stub = file_get_contents($this->getStub());
    }

    protected function getPathName(string $name): string
    {
        $name = substr($name, 4);

        return $this->app->getBasePath() . ltrim(str_replace('\\', '/', $name), '/') . '.php';
    }

    protected function getClassName(string $name): array
    {
        if (str_contains($name, '\\')) {
            return $name;
        }

        if (str_contains($name, '@')) {
            [$app, $name] = explode('@', $name);
        } else {
            $app = '';
        }

        if (str_contains($name, '/')) {
            $name = str_replace('/', '\\', $name);
        }

        return $this->getCreateDirName($app , $name);
    }

    /**
     * 读取控制器层
     * @param string $app
     * @return string
     */
    protected function getCreateDirName( string $app , string $name) : array
    {
        $type = [];

        foreach ($this->type as $names)
        {
//            if ($names == 'controller')
//            {
//                $suffix =  ($this->app->config->get('route.controller_suffix') ? 'Controller' : '');
//                $type[$names] = 'app' . ($app ? '\\' . $app : '')  . '\\' . $names  . "\\" . $name . $suffix;
//            }else{
//                $type[$names] = 'app' . ($app ? '\\' . $app : '')  . '\\' . $names. "\\" . $name;
//
//            }
            switch ($names)
            {
                case 'controller':
                    $suffix =  ($this->app->config->get('route.controller_suffix') ? 'Controller' : '');
                    $type[$names] = 'app' . ($app ? '\\' . $app : '')  . '\\' . $names  . "\\" . $name . $suffix;
                    break;
                case 'lists':
                    $type[$names] = 'app' . ($app ? '\\' . $app : '')  . '\\' . $names  . "\\" . $name . 'Lists';
                    break;
                case 'logic':
                    $type[$names] = 'app' . ($app ? '\\' . $app : '')  . '\\' . $names  . "\\" . $name . 'Logic';
                    break;
                default:
                    $type[$names] = 'app' . ($app ? '\\' . $app : '')  . '\\' . $names  . "\\" . $name;
            }
        }
        return  $type;
    }


}